<template>
  <div>
    <!--  面包屑-->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图-->
    <el-card>
<!--      分配权限的对话框-->
      <el-dialog
          v-model="setRightDialogVisible"
          title="提示"
          width="30%"
          :before-close="handleClose"
          @close="setRightDialogClosed"
      >

        <span>
           <el-tree ref="treeRef" show-checkbox :data="rightslist" :props="treeProps" @node-click="handleNodeClick" node-key="id" default-expand-all :default-checked-keys="defKeys"/>
        </span>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">
          确定
        </el-button>
      </span>
        </template>
      </el-dialog>
      <!--    添加角色按钮区域-->
      <el-row style="margin-bottom: 10px;">
        <el-col>
          <el-button type="primary" size="large" @click="addDialogRoles = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!--    角色列表区域-->
      <el-table :data="rolelist" border stripe>
        <!--        展开列-->
        <el-table-column type="expand">
          <template #="scope">
            <el-row :class="['bdbottom',i1 === 0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
<!--              渲染一级权限-->
              <el-col :span="5" >
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <el-icon><CaretRight /></el-icon>
              </el-col>
<!--              渲染二级和三级权限-->
              <el-col :span="19">
<!--              通过for循环 嵌套渲染二级权限-->
                <el-row :class="[i2 === 0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i><el-icon><CaretRight /></el-icon></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template #="scope">
            <div class="flex">
              <el-button type="primary" @click="showEditPen(scope.row)">
                <el-icon :size="15">
                  <EditPen/>
                </el-icon>
                编辑
              </el-button>
              <el-button type="danger" @click="RemoveDelete(scope.row)">
                <el-icon :size="15">
                  <Delete/>
                </el-icon>
                删除
              </el-button>
              <el-button type="warning" @click="showSetRightDialog(scope.row)">
                <el-icon :size="15">
                  <Setting/>
                </el-icon>
                分配权限
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    添加角色的对话框-->
    <el-dialog
        v-model="addDialogRoles"
        title="添加角色"
        width="50%"
        @close="editDialogClosed"
    >
     <span>
      <el-form
          ref="addRolesRefs"
          :model="addRoles"
          :rules="addRolesRefs"
          label-width="80px"
      >
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="addRoles.roleName"/>
    </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"/>
          </el-form-item>
      </el-form>
        </span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogRoles= false">取消</el-button>
        <el-button type="primary" @click="addRoleList">
          确认
        </el-button>
      </span>
      </template>

    </el-dialog>

    <!--    编辑用户的对话框-->
    <el-dialog
        v-model="addDialogEditPen"
        title="编辑角色"
        width="50%"
        @close="addDialogEditPenClose"
    >
     <span>
      <el-form
          ref="EditPenRefs"
          :model="EditPenRefsRoles"
          :rules="EditPenRefs"
          label-width="80px"
      >
        <el-form-item label="id" prop="id">
      <el-input v-model="EditPenRefsRoles.id" disabled/>
    </el-form-item>
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="EditPenRefsRoles.roleName"/>
    </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="EditPenRefsRoles.roleDesc"/>
          </el-form-item>
      </el-form>
        </span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogEditPen= false">取消</el-button>
        <el-button type="primary" @click="putRoleList">
          确认
        </el-button>
      </span>
      </template>

    </el-dialog>
  </div>
</template>
<script>


export default {
  data() {
    return {
      //     所有角色列表数据
      rolelist: [],
      // 所有权限的数据
      rightslist:[],

      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible:false,
      //   添加角色数据
      addDialogRoles: false,
      // 添加角色数据
      addRoles: {
        roleName: '',
        roleDesc: '',
      },
      // 添加用户表单的验证规则对象
      addRolesRefs: {
        roleName: [{
          required: true, message: '请输入角色名称',
          trigger: 'blur'
        }, {
          min: 3,
          max: 10,
          message: '用户名在3~10个字之间'
        }],
        roleDesc: [{
          required: true, message: '请输入角色描述',
          trigger: 'blur'
        }, {
          min: 3,
          max: 10,
          message: '用户名在3~10个字之间'
        }],
      },
      // 编辑角色数据
      addDialogEditPen: false,
      // 编辑角色数据
      EditPenRefsRoles: {
        children:[
          {
            "id": 104,
            "authName": "商品列表",
            "path": null,
          }
        ]
      },
      //   删除角色数据
      RemoveDeleteRoles: {},
    //   树状控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      defKeys:[],
      // 当前即将分配权限的角色id
      roleId:''

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色的列表
    async getRoleList() {
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 关闭对话框
    editDialogClosed() {
      this.$refs.addRolesRefs.resetFields()
    },

    // 添加角色
    addRoleList() {
      this.$refs.addRolesRefs.validate(
          async valid => {
            if (!valid) return this.$message.error('添加失败')
            // 发送用户添加请求
            const {data: res} = await this.$http.post('roles', this.addRoles)
            if (res.meta.status !== 201) return this.$message.error('添加失败')
            this.getRoleList()
            // 关闭添加对话框
            this.addDialogRoles = false
          }
      )

    },
    //   修改角色
    showEditPen(row) {
      this.addDialogEditPen = true
      this.EditPenRefsRoles = row
    },
    //   关闭对话框
    addDialogEditPenClose() {
      this.$refs.EditPenRefs.resetFields()
    },
    //   修改角色
    putRoleList() {
      this.$refs.EditPenRefs.validate(async valid => {
            if (!valid) return this.$message.error('修改失败')
            // console.log(typeof(this.EditPenRefsRoles.id))
            console.log(this.EditPenRefsRoles.id)
            const {data: res} = await this.$http.put(`roles/` + this.EditPenRefsRoles.id, {
              roleName: this.EditPenRefsRoles.roleName,
              roleDesc: this.EditPenRefsRoles.roleDesc
            })
            if (res.meta.status !== 200) return this.$message.error('修改失败')
            this.$message.success('修改成功')
            this.getRoleList()
            this.addDialogEditPen = false
          }
      )
    },
    //   删除角色
    async RemoveDelete(row) {
      //    弹窗提示用户是否删除
      const  config = await this.$confirm('此消息将永久删除该文件,是否继续','提示',{
        confirmButtonText:'确定',
        cancelButtonClass:'取消',
        type:'warning'
      }).catch(err => err)
      if (config !== 'confirm'){
        return this.$message.info('取消了删除')
      }
      this.RemoveDeleteRoles = row
      const {data: res} = await this.$http.delete('roles/' + this.RemoveDeleteRoles.id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getRoleList()

    },

  //  通过id删除对应的权限
   async removeRightById(role,rightId){
   //    弹窗提示用户是否删除
     const  config = await this.$confirm('此消息将永久删除该文件,是否继续','提示',{
       confirmButtonText:'确定',
       cancelButtonClass:'取消',
       type:'warning'
     })
     if (config !== 'confirm'){
       return this.$message.info('取消了删除')
     }
     const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
     if (res.meta.status !==200) {
       return this.$message.error('删除失败');
     }
     this.$message.success('删除成功')
     // this.getRoleList()
     // 防止页面重新渲染刷新
     role.children = res.data
   },
    // 显示分配权限的对话框
    async showSetRightDialog(role){
      this.roleId = role.id
      // 获取所有权限的数据
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200){
        return this.$message.error('获取权限数据')
      }
      this.rightslist = res.data
      this.getLeafKeys(role,this.defKeys)

        this.setRightDialogVisible= true
    },
  //   通过递归的形式,获取角色下所有三级权限的id,并保存到defkeys数组
    getLeafKeys(node,arr){
    //如果当前node节点不包括children属性,则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item,arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed(){
      this.defKeys = []
    },
  //   点击为角色分配权限
    async allotRights(){
      const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
     const {data:res} =  await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      console.log(res)
      if(res.meta.status !== 200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    }


  }
}
</script>
<style lang="scss" scoped>
.el-tag{
  margin:7px;
}
.bdbottom{
  border-bottom:1px solid #eeeeee ;
}
.bdtop{
  border-top: 1px solid #eeeeee;

}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
